<template>
    <div class="app-container">
        <base-info :opmode="mode" :id="modGoodsId" ref="baseInfoForm" />

        <price-info :opmode="mode" ref="priceInfoForm" />

        <attr-info :opmode="mode" ref="attrInfoForm" />

        <goods-detail ref="goodDetail" />
        <el-row class="operate-button" type="flex" justify="end">
            <el-button type="primary" @click="saveData">{{
                this.mode ? '修改' : '保 存'
            }}</el-button>
            <el-button @click="cancelData">取 消</el-button>
        </el-row>
    </div>
</template>
<script>
import { mapGetters } from 'vuex';
import baseInfo from './components/baseInfo';
import priceInfo from './components/priceInfo';
import attrInfo from './components/attrInfo';
import goodsDetail from './components/goodsDetail';
import { createGoods, getGoodsDetail, updateGoods } from '@/api/goodsBase';

export default {
    name: 'addProductInfo',
    computed: {
        ...mapGetters(['goodsDetailInfo'])
    },
    created() {
        let pathStr = this.$route.path;
        if (pathStr.indexOf('updateProduct') > -1) {
            this.mode = 1; // 改为修改模式
            this.modGoodsId = this.$route.params.id;
            // console.log("params goodid", this.modGoodsId);
            if (this.modGoodsId == null || this.modGoodsId == undefined) {
                this.$router.go('/404');
            }
            this.GoodsDetail(this.modGoodsId); // 发布数据

            //   // console.log(this.modGoodsId)
        } else if (pathStr.indexOf('addProduct') > -1) {
            this.mode = 0; // 改为添加模式
        }
    },
    components: { baseInfo, attrInfo, priceInfo, goodsDetail },
    data() {
        return {
            requestData: '',
            mode: 0, // mode 为0 为添加状态， mode 为1 为修改状态
            initialData: {},
            modGoodsId: '-1'
        };
    },
    methods: {
        saveData() {
            let vfBase = this.$refs['baseInfoForm'].validateForm();
            let vfPrice = this.$refs['priceInfoForm'].validateForm();
            let vfAttr = this.$refs['attrInfoForm'].validateForm();

            // // console.log(vfBase);
            Promise.all([vfBase, vfPrice, vfAttr]).then(
                res => {
                    //  // // console.log(this.$refs["baseInfoForm"]);
                    if (res) {
                        if (this.mode === 0) {
                            this.createGoods();
                        } else {
                            this.updateGoods();
                        }
                    }
                },
                err => {
                    this.$message.error('请按要求填写表单');
                }
            );
        },

        createGoods() {
            let reqData = this.getFormData(); // 目前的数据

            createGoods(reqData).then(res => {
                if (res.data && res.data.success) {
                    this.$message.success('新增商品成功');
                    this.$router.back(-1); // 回到原来的路由
                } else {
                    this.$message.error(res.data.msg);
                }
            });
        },
        updateGoods() {
            let reqData = this.getUpdateRequestData();
            updateGoods(reqData).then(res => {
                if (res.data.success == true) {
                    this.$message.success('修改成功');
                } else {
                    this.$message.error(res.data.msg);
                }
            });
        },
        GoodsDetail(id) {
            id = id ? id : this.modGoodsId;
            getGoodsDetail(id).then(res => {
                if (res.data.success == true) {
                    // 获取成功
                    this.modGoodDetailInfo = res.data.data;
                    return this.$store.dispatch('SetGoodsDetail', res.data.data).then(() => {
                        this.initialData = this.getFormData();
                        // console.log("initialData", this.initialData)
                    }); //发布数据
                    // // console.log(this.goodsDetailInfo)
                } else {
                    this.$message.error(res.data.msg);
                    this.$router.back(-1);
                }
            });
        },
        cloneDeep(obj) {
            return JSON.parse(JSON.stringify(obj));
        },
        getFormData() {
            // 深拷贝， 改变格式不影响原先值
            let baseformData = this.cloneDeep(this.$refs['baseInfoForm'].baseInfoForm);
            let goodsSku = this.cloneDeep(this.$refs['priceInfoForm'].priceInfoForm);
            let goodsAttr = this.cloneDeep(this.$refs['attrInfoForm'].goodsAttr);
            let detail = this.cloneDeep(this.$refs['goodDetail'].detailHtml);
            // cates 转化
            // cates string 转 json
            // baseformData.cates = baseformData.cates.map(el => el[el.length - 1])
            baseformData.cates = baseformData.cates.map(el => JSON.parse(el));
            this.requestData = {
                ...baseformData,
                goodsAttr: {
                    ...goodsAttr,
                    detail
                },
                goodsSku
            };

            return this.requestData;
        },
        getUpdateRequestData() {
            let beforeObj = this.initialData;
            let afterObj = this.getFormData();
            afterObj = {
                ...afterObj,
                cates: this.compareAndGetAdd(beforeObj.cates, afterObj.cates),
                delCateIds: this.compareAndGetDel(beforeObj.cates, afterObj.cates).map(el => el.id),
                imageUrls: this.compareAndGetAdd(beforeObj.imageUrls, afterObj.imageUrls),
                delImageResourceIds: this.compareAndGetImgDel(afterObj.imageUrls)
            };
            return afterObj;
        },
        compareAndGetAdd(beforeArr, afterArr) {
            return afterArr.filter(el => !beforeArr.includes(el));
        },
        compareAndGetDel(beforeArr, afterArr) {
            return beforeArr.filter(el => !afterArr.includes(el));
        },
        compareAndGetImgDel(afterUrls) {
            let imgInfoArr = this.goodsDetailInfo.resourceList;
            let deleteArr = imgInfoArr.filter(el => !afterUrls.includes(el.resourceUrl));
            return deleteArr.map(el => el.id);
        },
        cancelData() {
            this.$router.back(-1); // 回到原来的路由
        }
    }
};
</script>

<style scoped>
.operate-button {
    width: 900px;
    margin: 15px;
}
</style>
